package com.xyzk.diagnose.activity.bluetooth;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.xyzk.diagnose.R;
import com.xyzk.diagnose.activity.adapter.BluetoothDeviceAdapter;
//import com.xyzk.diagnose.activity.bluetoothGatt.BleBluetoothManager;
import com.xyzk.diagnose.entity.Cartype;
import com.xyzk.diagnose.tools.Common;
import com.xyzk.diagnose.tools.Commonfunc;
import com.xyzk.diagnose.view.CToast;
import com.xyzk.diagnose.view.dialog.ProgressDialog;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class BluetoothActivity extends Activity implements OnClickListener{
	private static final String TAG = "BluetoothDeviceListActivity";
	private Button btnReset,btnSearch;
	private Cartype cartype = Cartype.getInstance();
	private ListView mListView;
	private TextView tvShow;
	private BluetoothDeviceAdapter mDeviceAdapter;
	private List<HashMap<String,String>> mDeviceData = new ArrayList<HashMap<String,String>>();
	private BluetoothAdapter mBluetoothAdapter;
	private BluetoothService mBluetoothService = BluetoothService.getInstance();
	private BluetoothDevice mDevice;
	private ProgressDialog progressDialog;
//	private BleBluetoothManager bleBluetoothManager;
	private int position;//当前连接蓝牙列表序号

	public Handler mHandler= new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case Common.BLUE_UPDATE_LIST:
					if(Common.DEBUG) Log.i(TAG,"清除设备列表!");
					mDeviceData.clear();
					mDeviceAdapter.notifyDataSetChanged();
					Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
					for (BluetoothDevice device : pairedDevices){
						if(filterBluetoothName(device.getName())){//名字过滤
							HashMap<String,String> data = new HashMap<String,String>();
							data.put("deviceName", device.getName());
							data.put("deviceStatus", getString(R.string.bluetoothconnect_blue_connectnone));
							data.put("deviceMac", device.getAddress());
							data.put("devicePair", getString(R.string.bluetoothconnect_pair));
							mDeviceData.add(data);
							if(Common.DEBUG) Log.i(TAG,"加入已配对设备+" + device.getName());
						}
					}
					showDeviceList();
					mDeviceAdapter.notifyDataSetChanged();
					if(msg.arg1 == Common.BLUE_UPDATE_AND_SEARCH){//判断是否需要查找设备
						if(Common.DEBUG) Log.i(TAG,"查找设备...");
						if (mBluetoothAdapter.isDiscovering()) {
							mBluetoothAdapter.cancelDiscovery();//取消搜索
						}
						mBluetoothAdapter.startDiscovery();//开始搜索
						btnSearch.setClickable(false);//屏蔽查找按钮
						btnSearch.setText(R.string.bluetoothconnect_button_searching);
					}
					break;
				case Common.BLUE_ADD_LIST://添加未配对的蓝牙列表
					BluetoothDevice device = (BluetoothDevice)msg.obj;
					if(!filterBluetoothName(device.getName())) return;
					if(filterDuplicateName(device.getAddress())) return;
					HashMap<String,String> data = new HashMap<String,String>();
					data.put("deviceName", device.getName());
					data.put("deviceStatus", getString(R.string.bluetoothconnect_blue_connectnone));
					data.put("deviceMac", device.getAddress());
					data.put("devicePair", getString(R.string.bluetoothconnect_nopair));
					mDeviceData.add(data);
					showDeviceList();
					mDeviceAdapter.notifyDataSetChanged();
					if(Common.DEBUG) Log.i(TAG,"添加新搜索设备+" + device.getName());
					break;
				case Common.BLUE_RECEIVE_CONNECT://蓝牙连接消息
					progressDialog.dismiss();
					if (cartype.car.equals("T1PPHEV")){
						CToast.show("连接成功!");
						setConnectState(R.string.bluetoothconnect_blue_connected);
						setResult(Common.RESULT_OK, getIntent());
						finish();
					}else {
						if(mBluetoothService.isConnected()){
							CToast.show("连接成功!");
							setConnectState(R.string.bluetoothconnect_blue_connected);
							setResult(Common.RESULT_OK, getIntent());
							finish();
						}else{
							CToast.show("连接失败!");
							setConnectState(R.string.bluetoothconnect_blue_connectfail);
						}
					}
					break;
			}
		};
	};

	@Override
	protected synchronized void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bluetooth);
		setResult(Activity.RESULT_CANCELED);
		initViews();
		registerRecevie();
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if(mBluetoothAdapter == null){//判断是否有蓝牙设备
			setResult(Common.RESULT_FAIL,getIntent());
			finish();
		}
		new BluetoothThread().start();
	}

	/**
	 * 注册蓝牙监听广播
	 */
	private void registerRecevie(){
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mBluetoothReceiver, filter);
	}

	/**
	 * 初始化控件
	 */
	private void initViews(){
		btnReset = (Button) findViewById(R.id.bluetoothconnect_button_open);
		btnSearch = (Button) findViewById(R.id.bluetoothconnect_button_search);
		tvShow =(TextView) findViewById(R.id.tv_bluetoothconnect_textview);
		mListView = (ListView)findViewById(R.id.bluetoothconnect_listview);
		btnReset.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		showDeviceList();
		mDeviceAdapter = new BluetoothDeviceAdapter(mDeviceData);
		mListView.setAdapter(mDeviceAdapter);

		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
									long arg3) {
				position = arg2;
				pairBluetooth(mDeviceAdapter.getItem(arg2).get("deviceMac"));
			}
		});

		mListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo){
				AdapterContextMenuInfo menuInfo1 = (AdapterContextMenuInfo)menuInfo;
				int pos = (int)mDeviceAdapter.getItemId(menuInfo1.position);
				HashMap<String,String> now = mDeviceAdapter.getItem(pos);
				menu.setHeaderTitle(now.get("deviceName"));
				int i = 0;
				BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(now.get("deviceMac"));
				if(device.getBondState() == BluetoothDevice.BOND_BONDED){//已经配对添加取消配对
					menu.add(0,i++,0,R.string.bluetoothconnect_set_cancelpair);
				}
				menu.add(0,i++,0,R.string.bluetoothconnect_button_return);
			}
		});

	}

	@Override//长按list出现的菜单点击实现方法
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
		int pos = (int)mDeviceAdapter.getItemId(menuInfo.position);
		HashMap<String,String> now =mDeviceAdapter.getItem(pos);
		switch(item.getItemId()){
			case 0:
				if(Common.DEBUG) Log.i(TAG,"取消配对：" + pos);
				BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(now.get("deviceMac"));
				removeBond(device);
				break;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.bluetoothconnect_button_open:
				if(mBluetoothService.isConnected()){
					mBluetoothService.stopService();
				}
				new ResetBluetoothThread().start();
				break;
			case R.id.bluetoothconnect_button_search:
				mHandler.obtainMessage(Common.BLUE_UPDATE_LIST,Common.BLUE_UPDATE_AND_SEARCH,0).sendToTarget();
				break;
		}
	}

	/**
	 * 有蓝牙设备就显示设备列表，无则显示TextView提示
	 */
	private void showDeviceList(){
		if(mDeviceData.size() == 0){
			tvShow.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
		}else{
			tvShow.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 配对蓝牙
	 * @param addr MAC地址
	 */
	private  void pairBluetooth(String addr){
//		if ("T1PPHEV".equals(cartype.car)){
//			progressDialog = ProgressDialog.createDialog(BluetoothActivity.this,"正在连接蓝牙...");
//			setConnectState(R.string.bluetoothconnect_blue_connecting);
//			mDevice=mBluetoothAdapter.getRemoteDevice(addr);
//			bleBluetoothManager=new BleBluetoothManager(this);
//			bleBluetoothManager.connectBle(mDevice);
//			mHandler.obtainMessage(Common.BLUE_RECEIVE_CONNECT,1,0).sendToTarget();
//		}else {
			progressDialog = ProgressDialog.createDialog(BluetoothActivity.this,"正在连接蓝牙...");
			if(!mBluetoothAdapter.isEnabled()){//先判断蓝牙是否打开
				CToast.show(R.string.bluetoothconnect_tip_bluecancel);
				return;
			}
			if(mBluetoothAdapter.isDiscovering()){//先取消搜索
				mBluetoothAdapter.cancelDiscovery();
			}
			btnSearch.setClickable(true);
			btnSearch.setText(R.string.bluetoothconnect_button_search);
			BluetoothDevice dev = mBluetoothAdapter.getRemoteDevice(addr);
			if(dev.getBondState() != BluetoothDevice.BOND_BONDED){//未配对就配对
				createBond(dev);
			}
			setConnectState(R.string.bluetoothconnect_blue_connecting);
			connectBluetooth(addr);
//		}
	}

	/**
	 * 连接蓝牙
	 * @param mac MAC地址
	 */
	private void connectBluetooth(String mac){
		mBluetoothService.setHandler(mHandler);
		mBluetoothService.connectDevice(mac);
	}

	/**
	 * 设置蓝牙状态显示
	 * @param state
	 */
	private void setConnectState(int resId){
		HashMap<String,String> now =mDeviceAdapter.getItem(position);
		now.put("deviceStatus",getString(resId));
		mDeviceAdapter.notifyDataSetChanged();
	}


	/**
	 * 启动蓝牙线程
	 */
	private class BluetoothThread extends Thread {
		@Override
		public void run() {
			super.run();
			while(true){
				if(!mBluetoothAdapter.isEnabled()){
					mBluetoothAdapter.enable();//打开蓝牙
					Commonfunc.sleep(200);
				}else{
					mHandler.obtainMessage(Common.BLUE_UPDATE_LIST,0,0).sendToTarget();
					Commonfunc.sleep(500);
					break;
				}
			}
		}
	}

	/**
	 * 重置线程
	 */
	private class ResetBluetoothThread extends Thread {
		@Override
		public void run() {
			super.run();
			if(mBluetoothAdapter.isEnabled()){
				while(true){
					if(mBluetoothAdapter.disable()){
						if(Common.DEBUG) Log.i(TAG,"重置关闭蓝牙设备!");
						break;
					}
					Commonfunc.sleep(500);
				}
			}
			while(true){
				Commonfunc.sleep(500);
				if(mBluetoothAdapter.isEnabled()){
					mHandler.obtainMessage(Common.BLUE_UPDATE_LIST).sendToTarget();
					break;
				}else{
					if(mBluetoothAdapter.enable()){
						if(Common.DEBUG) Log.i(TAG,"重置打开蓝牙设备!");
						break;
					}
				}
			}
		}
	}

	@Override
	protected synchronized void onDestroy() {
		if (mBluetoothAdapter != null) {
			mBluetoothAdapter.cancelDiscovery();
		}
		this.unregisterReceiver(mBluetoothReceiver);
		super.onDestroy();
	}

	private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent){
			String action = intent.getAction();
			if(Common.DEBUG) Log.i(TAG,"接收消息：" + action);
			if (BluetoothDevice.ACTION_FOUND.equals(action)){
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if(device.getBondState() != BluetoothDevice.BOND_BONDED){//未配对
					if (device.getName() == null || (device.getName()).equals("") || (device.getName()).equals("null")){
					}
					else {
						HashMap<String,String> data = new HashMap<String,String>();
						data.put("deviceName", device.getName());
						data.put("deviceStatus", getString(R.string.bluetoothconnect_blue_connectnone));
						data.put("deviceMac", device.getAddress());
						data.put("devicePair", getString(R.string.bluetoothconnect_nopair));
						mDeviceData.add(data);
						showDeviceList();
						mDeviceAdapter.notifyDataSetChanged();
					}
				}
			}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
				if(Common.DEBUG) Log.e(TAG,"查找结束");
				btnSearch.setClickable(true);
				btnSearch.setText(R.string.bluetoothconnect_button_search);
			}else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
				if(Common.DEBUG) Log.e(TAG,"ACTION_BOND_STATE_CHANGED");
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				for(int i = 0; i < mDeviceAdapter.getCount(); i ++){
					HashMap<String,String> now =mDeviceAdapter.getItem(i);
					if((now.get("deviceMac")).equals((device.getAddress()))){
						if(device.getBondState() == BluetoothDevice.BOND_BONDED){
							now.put("devicePair", getString(R.string.bluetoothconnect_pair));
							setConnectState(R.string.bluetoothconnect_blue_connectnone);
							connectBluetooth(device.getAddress());
						}else{
							now.put("devicePair", getString(R.string.bluetoothconnect_nopair));
						}
						break;
					}
				}
				mDeviceAdapter.notifyDataSetChanged();
			}
		}
	};


	/**
	 * 增加名字过滤，只显示launch和DBS开头的蓝牙
	 * @param name 设备名称
	 * @return
	 */
	private boolean filterBluetoothName(String name){
		return name.contains("3301")||name.contains("8801")?true:false;
	}

	/**
	 * 增加重复查找的列表显示，过滤重复的设备名,查找到则返回成功
	 * @param list
	 * @param macname
	 * @return
	 */
	private boolean filterDuplicateName(String macname){
		for(int i = 0; i < mDeviceData.size(); i ++){
			HashMap<String,String> data = mDeviceData.get(i);
			if(data.get("deviceMac").equals(macname))
				return true;
		}
		return false;
	}

	public static  boolean createBond(BluetoothDevice btDevice){
		try {
			Method	createBondMethod =btDevice.getClass().getMethod("createBond");
			Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
			return returnValue.booleanValue();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static  boolean removeBond(BluetoothDevice btDevice){
		try{
			Method removeBondMethod =btDevice.getClass().getMethod("removeBond");
			Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
			return returnValue.booleanValue();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
